<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
            v-model="queryParams.userId"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试卷ID" prop="paperId">
        <el-input
            v-model="queryParams.paperId"
            placeholder="请输入试卷ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题目ID" prop="questionId">
        <el-input
            v-model="queryParams.questionId"
            placeholder="请输入题目ID"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in dict.type.pgstatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专项类型" prop="type">
                    <el-select v-model="queryParams.type" placeholder="请选择题目类型" clearable>
                      <el-option
                          v-for="dict in dict.type.slquestion_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:correct:edit']"
        >批改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:correct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:correct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="correctList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="user_id" />
      <el-table-column label="试卷ID" align="center" prop="paper_id" />
      <el-table-column label="题目ID" align="center" prop="question_id" />
      <el-table-column label="答题时间" align="center" prop="dttime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dttime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批改时间" align="center" prop="pgtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pgtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pgstatus" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:correct:edit']"
          >批改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:correct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改批改管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        
        <el-form-item label="学生ID" prop="user_id">
	<el-input v-model="form.user_id" placeholder="学生ID" readonly />
</el-form-item>
        
        <!-- 显示材料 -->
        <div v-if="materials.length > 0">
          <el-divider>给定资料</el-divider>
          <div v-for="(material, index) in materials" :key="'material-' + index">
            <el-form-item :label="'资料' + getChineseNumber(index + 1)">
              <editor v-model="materials[index]" :min-height="192" read-only />
            </el-form-item>
          </div>
        </div>

        <!-- 显示题干 -->
        <div v-if="content.length > 0">
          <el-divider>作答要求</el-divider>
          <div v-for="(contentItem, index) in content" :key="'content-' + index">
            <el-form-item :label="getChineseNumber(index + 1)">
              <editor v-model="content[index]" :min-height="192" read-only />
            </el-form-item>
          </div>
        </div>
        
        <!-- 显示参考答案 -->
        <div v-if="suggestedAnswers.length > 0">
          <el-divider>参考答案</el-divider>
          <div v-for="(answer, index) in suggestedAnswers" :key="'suggested-answer-' + index">
            <el-form-item :label="'答案' + getChineseNumber(index + 1)">
              <editor v-model="suggestedAnswers[index]" :min-height="192" read-only />
            </el-form-item>
          </div>
        </div>

        <!-- 显示用户答案 -->
        <div v-if="userAnswers.length > 0">
          <el-divider>用户答案</el-divider>
          <div v-for="(answer, index) in userAnswers" :key="'user-answer-' + index">
            <el-form-item :label="'答案' + getChineseNumber(index + 1)">
              <editor v-model="userAnswers[index]" :min-height="192" placeholder="学生未作答" read-only />
            </el-form-item>
            <el-form-item :label="'点评' + getChineseNumber(index + 1)">
              <div class="editor-wrapper">
                <editor v-model="form.teacherAnswers[index]" :min-height="192" placeholder="请输入点评" />
              </div>
            </el-form-item>
            <el-form-item :label="'成绩' + getChineseNumber(index + 1)">
              <el-input v-model="form.grade[index]" placeholder="请输入成绩" />
            </el-form-item>
          </div>
        </div>
      </el-form>      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCorrect, getCorrect, delCorrect, addCorrect, updateCorrect } from "@/api/business/correct";
import { getSlquestion } from "@/api/business/slquestion";
import { getSlpaper } from "@/api/business/slpaper";

export default {
  name: "Correct",
  dicts: ['pgstatus', 'slquestion_type'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      correctList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        paperId: null,
        questionId: null,
        status: null,
        type: null
      },
      materials: [],
      content: [],
      suggestedAnswers: [],
      userAnswers: [],
      form: {
        teacherAnswers: [],
        grade: []
      },
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listCorrect(this.queryParams).then(response => {
        this.correctList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        user_id: null,
        paper_id: null,
        question_id: null,
        user_answers: null,
        status: null,
        grade: [],
        teacherAnswers: []
      };
      this.resetForm("form");
      this.materials = [];
      this.content = [];
      this.suggestedAnswers = [];
      this.userAnswers = [];
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCorrect(id).then(response => {
        this.form = response.data;
        this.form.teacherAnswers = JSON.parse(response.data.teacher_answers || '[]');
        this.form.grade = JSON.parse(response.data.grade || '[]');
        this.open = true;
        this.title = "修改批改管理";
        if (this.form.paper_id) {
          getSlpaper(this.form.paper_id).then(res => {
            if (res.data) {
              this.materials = JSON.parse(res.data.materials || '[]');
              this.content = JSON.parse(res.data.content || '[]');
              this.suggestedAnswers = JSON.parse(res.data.suggestedAnswer || '[]');
              this.userAnswers = JSON.parse(this.form.user_answers || '[]');
            } else {
              this.materials = [];
              this.content = [];
              this.suggestedAnswers = [];
              this.userAnswers = [];
            }
          }).catch(() => {
            this.materials = [];
            this.content = [];
            this.suggestedAnswers = [];
            this.userAnswers = [];
          });
        } else if (this.form.question_id) {
          getSlquestion(this.form.question_id).then(res => {
            if (res.data) {
              this.materials = JSON.parse(res.data.materials || '[]');
              this.content = JSON.parse(res.data.content || '[]');
              this.suggestedAnswers = JSON.parse(res.data.suggestedAnswer || '[]');
              this.userAnswers = JSON.parse(this.form.user_answers || '[]');
            } else {
              this.materials = [];
              this.content = [];
              this.suggestedAnswers = [];
              this.userAnswers = [];
            }
          }).catch(() => {
            this.materials = [];
            this.content = [];
            this.suggestedAnswers = [];
            this.userAnswers = [];
          });
        }
      }).catch(() => {
        this.materials = [];
        this.content = [];
        this.suggestedAnswers = [];
        this.userAnswers = [];
      });
    },
    getChineseNumber(num) {
      const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return chineseNumbers[num] || '';
    },
    submitForm() {
  this.$refs["form"].validate(valid => {
    if (valid) {
      // 设置 pgtime 为当前时间
      this.form.pgtime = new Date().toISOString(); // 将当前时间格式化为 ISO 字符串
      this.form.status = '1'; // 设置状态为 1

      // 将 teacherAnswers 和 grade 转换为 JSON 字符串
      this.form.teacher_answers = JSON.stringify(this.form.teacherAnswers);
      this.form.grade = JSON.stringify(this.form.grade);

      if (this.form.id != null) {
        updateCorrect(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addCorrect(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(() => {
        return delCorrect(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('business/correct/export', { ...this.queryParams }, `correct_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>

<style scoped>
.editor-wrapper {
  background-color: 	#F0F8FF;
}
</style>